<!--
 * @Description: 流程中心框架页
 * @Author: seadon
 * @LastEditors: seadon
 * @Date: 2021-07-08 16:06:53
 * @LastEditTime: 2022-03-14 18:57:04
-->
<template>
	<div class="pok-process-center process-center-custom-s">
		<TabSkeleton v-if="countLoading || !isTab" />

		<a-tabs
			v-else
			class="pok-process-tabs"
			:class="{ 'pok-process-layout': !isChangeLayout }"
			:active-key="getActiveTab"
			@change="handleChangeTask"
		>
			<a-tab-pane
				v-for="typeItem in taskCountRef"
				:key="typeItem.route_name"
				:tab="`${typeItem.title}${
					typeItem.count !== 0 ? (`${typeItem.route_name}`==='TaskNotice'?`(${typeItem.count+userNotifyNoReadTotal})`:`(${typeItem.count})`) : (`${typeItem.route_name}`==='TaskNotice'?  (`${typeItem.count+userNotifyNoReadTotal}`==='0'? '': `(${typeItem.count+userNotifyNoReadTotal})`)   : '')
				}`"
			></a-tab-pane>
		</a-tabs>
		<div
			class="changeLayout"
			@click="changeLayout"
			v-if="getActiveTab !== 'Drafts' && getActiveTab!=='TaskNotice'"
		>
			<div class="changeLayout-text">
				<i
					class="protalicon layout-icon"
					:class="isChangeLayout === true ? 'icon-buju-03' : 'icon-buju-01'"
				></i>
				<span>{{ $t('pages.process.layoutSwitching', '布局切换') }}</span>
			</div>
		</div>
		<div :class="{ 'pok-process-table': !isChangeLayout }">
      <PokToolBarNotice
        v-if="getActiveTab === 'TaskNotice'"
        @noticeTypeChange="noticeTypeChange"
      >
      </PokToolBarNotice>


			<pok-tool-bar
				ref="toolElRef"
        v-if="noticeType === 'flow'"
				:task-loading="taskLoading"
				:check-options="optionsListRef"
				:check-data="checkedListRef"
				:check-total="totalTaskTypeRef"
				:check-agent-options="optionsAgentListRef"
				:check-agent-data="checkedAgentListRef"
				:check-agent-total="totalAgentTaskTypeRef"
				:task-type="getActiveTab"
				:cache-data="tempQueryInfo"
				:selected-rows="selectedRows"
				:agree-promise="handleBatchAgree"
				:batch-promise="handleBatchAllRead"
				:delete-promise="handleDeleteDraft"
				:apply-count="applyCount"
				:done-type="doneType"
				:is-requesting="isRequesting"
				:is-change-layout="isChangeLayout"
				:select-type="selectType"
				:task-count-ref="taskCountRef"
				@on-search="handleSearch"
				@on-clear-select="handleClearSelect"
				@update-type-key-list-event="updateTypeKeyListEvent"
				@update-agent-id-event="updateAgentIdEvent"
				@get-select-typeList="getSelectTypeList"
				@get-reset-val="getResetVal"
			>
				<template #bidButton>
					<a-radio-group
						v-model:value="doneType"
						button-style="solid"
						@change="doneTypesChange"
					>
						<a-radio-button value="own">{{
							$t('pages.process.groupName.myDone', '我的已办')
						}}</a-radio-button>
						<a-radio-button value="bid">{{
							$t('pages.process.groupName.bidDone', '竞签已办')
						}}</a-radio-button>
						<a-radio-button value="agent">{{
							$t('pages.process.groupName.agentDone', '代理已办')
						}}</a-radio-button>
					</a-radio-group>
				</template>
			</pok-tool-bar>
			<div class="pok-process-table-right" v-if="noticeType === 'flow'">
				<tool-bar2
					v-if="!isChangeLayout"
					ref="toolElRef2"
					:task-loading="taskLoading"
					:check-options="optionsListRef"
					:check-data="checkedListRef"
					:check-total="totalTaskTypeRef"
					:check-agent-options="optionsAgentListRef"
					:check-agent-data="checkedAgentListRef"
					:check-agent-total="totalAgentTaskTypeRef"
					:task-type="getActiveTab"
					:cache-data="tempQueryInfo"
					:selected-rows="selectedRows"
					:agree-promise="handleBatchAgree"
					:batch-promise="handleBatchAllRead"
					:delete-promise="handleDeleteDraft"
					:apply-count="applyCount"
					:done-type="doneType"
					:is-requesting="isRequesting"
					:is-change-layout="isChangeLayout"
					:select-type-list="selectTypeList"
					:selectTypeStatus="selectTypeStatus"
					:is-reset-val="isResetVal"
					@on-search="handleSearch"
					@on-clear-select="handleClearSelect"
					@update-type-key-list-event="updateTypeKeyListEvent"
					@update-agent-id-event="updateAgentIdEvent"
					@get-select-type="getSelectType"
				>
				</tool-bar2>
				<pok-base-table
					v-if="columnsRef"
					ref="tableElRef"
					class="pok-base-table"
					:loading="getLoading"
					:data-source="
						store.state[
							getActiveTab === 'DoneTask'
								? doneType === 'own'
									? 'DoneTask'
									: doneType === 'bid'
									? 'bidDoneTask'
									: 'AgentDoneTask'
								: getActiveTab
						].data
					"
					:columns="columnsRef"
					:scroll="{ x: '100%', y:app_launcher?'calc(100vh - 290px)' : 'calc(100vh - 340px)'}"
					:custom-row="handleOperateRow"
					:row-key="rowKeyRefFun"
					:is-change-layout="isChangeLayout"
					@table-change="handleTableChange"
				>
					<template #custom-title="{ record, index }">
						<div class="title">
							<div
								v-if="
									(tenantDetail.tenant_auth?.batch_approve &&
										(getActiveTab === 'TodoTask' ||
											getActiveTab === 'AgentTodo')) ||
									getActiveTab === 'Drafts'
								"
								class="title-checkbox"
							>
								<a-checkbox
									:indeterminate="titleIndeterminate"
									:checked="titleCheckAll"
									:disabled="titleDisabled"
									@change="titleChange"
								></a-checkbox>
							</div>
							<div v-else class="title-serial">
								{{ $t('informationPortal.SerialNumber', '序号') }}
							</div>
						</div>
					</template>
					<template #custom-index="{ record, index }">
						<div
							v-if="
								getActiveTab === 'TodoTask' ||
								getActiveTab === 'Drafts' ||
								getActiveTab === 'AgentTodo'
							"
							class="index"
							:class="[
								titleCheckAll || record.checked || processVersion === '2'
									? 'index-active'
									: '',
								tenantDetail.tenant_auth?.batch_approve ||
								getActiveTab === 'Drafts'
									? 'index-hover'
									: '',
							]"
							@click.stop="() => {}"
						>
							<div class="index-checkbox">
								<a-tooltip
									v-if="
										tenantDetail.tenant_auth?.batch_approve ||
										getActiveTab === 'Drafts'
									"
									:title="
										record.disable
											? $t(
													'pages.process.singleCheckBoxTip',
													'该任务不可批量审批'
											  )
											: ''
									"
								>
									<a-checkbox
										v-model:checked="record.checked"
										:disabled="record.disable"
										@change="onChange(record)"
										@click.stop="() => {}"
									></a-checkbox>
								</a-tooltip>
							</div>
							<div class="index-serial">
								{{
									processVersion !== '2'
										? (pageIndexRef - 1) * pageSizeRef + index + 1
										: ''
								}}
							</div>
						</div>
						<div v-else class="index">
							{{ (pageIndexRef - 1) * pageSizeRef + index + 1 }}
						</div>
					</template>
					<template #custom-subject>
						<div class="subject-title">
							{{ $t('pages.process.column.name', '流程名称') }}
							<a-popover
								placement="bottomRight"
								trigger="click"
								v-model:visible="subjectVisible"
								arrow-point-at-center
								v-if="doneType === 'own'"
							>
								<template #content>
									<a-checkbox
										v-model:checked="subjectChecked"
										@change="changeMergeChecked"
										>{{
											$t(
												'pages.process.select.mergeInfo',
												'同一条流程仅展示最新一条已办'
											)
										}}</a-checkbox
									>
								</template>
								<i
									:class="[
										'low-code',
										'iconyidongduan-shaixuan',
										subjectVisible ? 'active' : '',
									]"
									@click="subjectVisible = true"
								/>
							</a-popover>
						</div>
					</template>
					<template #custom-serial-number="{ record, index }">
						<div
							v-if="
								processVersion == 2 &&
								(getActiveTab === 'TodoTask' ||
									getActiveTab === 'Drafts' ||
									getActiveTab === 'AgentTodo')
							"
							class="index"
						>
							{{ (pageIndexRef - 1) * pageSizeRef + index + 1 }}
						</div>
					</template>
					<template #custom-person="{ record }">
						<div
							v-if="record?.initiator || record?.creator"
							class="custom-person"
						>
							<div>
								<ok-person-cell
									width="30px"
									height="30px"
									.person-info="record.initiator || record?.creator"
								>
								</ok-person-cell>
							</div>
							<div class="person-info">
								<div id="person-s" class="primary-text">
									<EllipsisTooltip
										:title="
											record.initiator?.employee_name ||
											record?.creator?.employee_name
										"
									/>
								</div>
								<div class="descript-text">
									<EllipsisTooltip
										:title="
											record.initiator?.department_name ||
											record?.creator?.department_name
										"
									/>
								</div>
							</div>
						</div>
					</template>
					<template #custom-person-group="{ record }">
						<div v-if="record?.task_assignee_list" class="custom-person-group">
							<div>
								<ok-person-group
									v-if="record.task_assignee_list.length > 1"
									.person-list="record.task_assignee_list"
									placement="right"
									.show-all="true"
								></ok-person-group>
								<div
									v-else-if="record.task_assignee_list.length === 1"
									class="custom-person"
								>
									<div>
										<ok-person-cell
											width="30px"
											height="30px"
											.person-info="record.task_assignee_list[0]"
										></ok-person-cell>
									</div>
									<div class="person-info">
										<div class="primary-text">
											<EllipsisTooltip
												:title="record.task_assignee_list[0]?.employee_name"
											/>
										</div>
										<div class="descript-text">
											<EllipsisTooltip
												:title="record.task_assignee_list[0]?.department_name"
											/>
										</div>
									</div>
								</div>
								<template v-else> -- </template>
							</div>
						</div>
					</template>
					<template #custom-operate="{ record }">
						<div class="custom-operate">
							<a-space :size="24">
								<a-button type="link" @click.stop="handleEditDraft(record)">
									{{ iTrans('common.edit', '编辑') }}
								</a-button>
								<a-button type="link" @click.stop="onDelete(record)">
									{{ iTrans('common.delete', '删除') }}
								</a-button>
							</a-space>
						</div>
					</template>
				</pok-base-table>
			</div>
      <div v-if="noticeType==='todo'" style="margin-top: 20px">
        <a-table :dataSource="userNotifyAllRows" :columns="userNotifyColumns" :loading="notifyLoading" :pagination="false">
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.dataIndex === 'operation'">
            <div class="custom-operate">
              <a-space :size="24">
                <a-button type="ghost" @click.stop="viewNotify(record)">
                  查看
                </a-button>
                <a-button  type="ghost" v-if="record.formUrl" @click.stop="toForm(record)">
                  填写表单
                </a-button>
              </a-space>
            </div>
          </template>
          <template v-if="column.dataIndex === 'isRead'">
            <div>
             {{text === 0 ?'未读':'已读'}}
            </div>
          </template>
        </template>
        </a-table>
        <a-pagination
          v-model:current="userNotifyPageNum"
          class="process-pagination"
          size="small"
          show-size-changer
          :total="
				userNotifyTotal
			"
          :page-size="userNotifyPageSize"
          :page-size-options="pageSizeOptions"
          :show-total="userNotifyTotal => $t('common.showTotal', `共 ${userNotifyTotal} 条`, { userNotifyTotal })"
          @show-size-change="userNotifySizeChange"
          @change="userNotifyTableChange"
        />
      </div>
      <a-modal v-model:visible="notifyOpen" title="知会内容" @ok="handleOk">
        <div v-html="notifyContent"> </div>
      </a-modal>
		</div>


		<a-pagination
      v-if="noticeType === 'flow'"
			v-show="!getLoading"
			v-model:current="pageIndexRef"
			class="process-pagination"
			size="small"
			show-size-changer
			:total="
				store.state[
					getActiveTab === 'DoneTask'
						? doneType === 'own'
							? 'DoneTask'
							: doneType === 'bid'
							? 'bidDoneTask'
							: 'AgentDoneTask'
						: getActiveTab
				]?.total
			"
			:page-size="pageSizeRef"
			:page-size-options="pageSizeOptions"
			:show-total="total => $t('common.showTotal', `共 ${total} 条`, { total })"
			@show-size-change="onShowSizeChange"
			@change="tableChange"
		/>
	</div>
</template>

<script setup lang="ts">
import {
	computed,
	ref,
	unref,
	onMounted,
	onBeforeUnmount,
	watch,
	nextTick,
	createVNode,
	reactive,
} from 'vue'
import type { Ref } from 'vue'
import { useStore } from 'vuex'
import { debounce } from 'lodash'
import { Modal, message } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { i18n } from '@/locales'
import loadingMore from '@/directives/loadingMore'
import { taskTypeEnum } from '@/constant/enums/processCenter'
import EllipsisTooltip from '@/entry_desktop/components/EllipsisTooltip'
import { BaseTable as PokBaseTable } from '@/entry_desktop/components/BaseTable'
import { TabSkeleton } from './skeleton'
import PokToolBar from './ToolBar.vue'
import PokToolBarNotice from './ToolBarNotice.vue'
import useModel from './hooks/useModel'
import userNotifyModel from '../Home/components/HomeUserInfo/useModel'
import useTable from './hooks/useTable'
import type { IUpdateListParams } from './type'
import { taskSelect } from './constant'
import ToolBar2 from './ToolBar2.vue'
import './index.less'

const {
  userNotifyNoReadTotal,
  userNotifyAllRows,
  fetchUserNotify,
  userNotifyTotal,
  fetchUserAllNotify,
  userNotifyColumns,
  updateUserNotify,
  userNotifyUpdateCode,
  notifyLoading,
} = userNotifyModel()
const userInfo = computed(() => store.state.userInfo)
const { $t: iTrans } = i18n
const store = useStore()
const { changeMergeChecked: questChangeMerge } = useModel() as any
const tempQueryInfo: Ref<Recordable<any>> = ref({})
const tempListType = ref()
const toolElRef = ref()
const toolElRef2 = ref()
const searchTypeVal = ref()
const app_launcher=ref()
const tableElRef = ref<ComponentRef>()
const total = ref()
const noticeType = ref('flow')
let notifyContent = ref('')
const notifyOpen = ref<boolean>(false)

const tenantDetail: any = computed(() => store.state.tenant)
let localChecked = localStorage.getItem('subjectChecked')
const subjectChecked = ref(
	localChecked ? (localChecked == 'true' ? true : false) : false
)
if (!localChecked) {
	localStorage.setItem('subjectChecked', 'false')
}
const subjectVisible = ref(false)
const processVersion = computed(() => {
	let version = '1'
	if (tenantDetail.value?.channel_json) {
		const processListVersion = JSON.parse(
			tenantDetail.value.channel_json
		).process_list_version
		version = processListVersion
	}
	return version
})

//分页
const pageSizeOptions = ref<string[]>(['10', '20', '30', '40', '50']) //定义每页条数
const userNotifyPageNum = ref(1)
const userNotifyPageSize = ref(10)
const {
	pageIndexRef,
	pageSizeRef,
	// total,
	initProcessCenter,
	getLoading,
	taskLoading,
	countLoading,
	listDataRef, // 表格数据源
	taskCountRef, // 流程任务数量
	checkedListRef, // 选中列表数据
	optionsListRef, // 流程任务数据供筛选下拉框使用
	totalTaskTypeRef, // 全部任务总计
	getActiveTab,
	isTab,
	setActiveTab,
	setTaskLoading,
	batchAgree,
	batchAllReaded,
	deleteDraft,
	fetchTableList,
	fetchTaskCount,
	fetchApplyFilterList,
	totalAgentTaskTypeRef,
	optionsAgentListRef,
	checkedAgentListRef,
	fetchCountAgentTask,
	fetchApplyCount,
	fetchTaskNoticeCount,
	fetchDoneTaskCount,
	fetchBidDoneTaskCount,
	applyCount, // 我的申请数量
	titleCheckAll,
	titleDisabled,
	titleIndeterminate,
	titleChange,
	selectedRows,
	onChange,
	handleClearSelect,
	handleSetSelectState,
	doneTypesChange,
	doneType,
	isRequesting,
	fetchAgentDoneTaskCount,
} = useModel(tenantDetail) as any
// 左右布局时 获取左侧筛选数据
let selectTypeList = ref()
let selectTypeStatus = ref()
const getSelectTypeList = (val: any) => {
	selectTypeList.value = val[0]
	selectTypeStatus.value = val[1]
}

const rowKeyRefFun = (val: any, index: any) => {
	return val[rowKeyRef.value] + new Date().getTime()
}
// 获取右侧 审批 知会 等筛选类型
let selectType = ref()
const getSelectType = (val: any) => {
	selectType.value = val
}
let isResetVal = ref(false)
const getResetVal = (val: any) => {
	isResetVal.value = val
}

const viewNotify = (val: any) => {
  notifyContent.value = val.content
  notifyOpen.value = true;
  if (val.isRead === 0) {
    updateUserNotify(val.id,1);
  }
  for (let userNotifyAllRowsKey of userNotifyAllRows.value) {
    if (userNotifyAllRowsKey.id === val.id) {
      userNotifyAllRowsKey.isRead = 1;
    }
  }
}

const handleOk = (e: MouseEvent) => {
  notifyOpen.value = false;
};

const toForm = (val: any) => {
  let origin = window.location.origin
  let originalPath = val.formUrl
  let partToRemove = "/multipleTabs";
  let newPath = origin + originalPath.replace(partToRemove, "").toLowerCase();
  window.open(newPath)
}

// 搜索
const handleSearch = (
	{
		subject,
		type_key_list,
		agent_id,
		total_count_data,
		agent_id_total,
		...params
	}: IUpdateListParams,
	type = '',
	isFirst = true
) => {
	let listType, extraParams
	// listType判断

	if ((params as any)?.type) {
		const { type, ...restParams } = params as any
		listType = type
		extraParams = restParams
		extraParams.listType = listType
		tempListType.value = listType
	} else {
		extraParams = params
	}
	// 查询条件叠加
	const queryInfo = {
		time_sort: 'desc',
		...unref(tempQueryInfo)?.[unref(getActiveTab)],
		subject: unref(toolElRef)?.subjectRef || unref(toolElRef2)?.subjectRef,
		type_key_list:
			type_key_list ??
			unref(tempQueryInfo)?.[unref(getActiveTab)]?.type_key_list,
		total_count_data: unref(total_count_data) ?? '',
		agent_id: unref(agent_id) ?? '',
		agent_id_total: unref(agent_id_total) ?? '',
		listType: unref(type) ?? 'todo',
		...extraParams,
	}

	// 缓存查询数据
	unref(tempQueryInfo)[unref(getActiveTab)] = queryInfo

	// 全部流程select失去焦点 && tab页为代理待办 触发
	if (type == 'allOption' && taskTypeEnum.AgentTodo === unref(getActiveTab)) {
		unref(tempQueryInfo)[unref(getActiveTab)].agent_id = ''
		fetchCountAgentTask(unref(tempQueryInfo)[unref(getActiveTab)])
	}

	const tabData = unref(tempQueryInfo)?.[unref(getActiveTab)]
	if (unref(getActiveTab) === 'Apply') {
		fetchApplyCount(tabData)
	}
	if (unref(getActiveTab) === 'TaskNotice') {
		fetchTaskNoticeCount(tabData)
	}
	if (unref(getActiveTab) === 'DoneTask') {
		unref(doneType) === 'own'
			? fetchDoneTaskCount(queryInfo)
			: unref(doneType) === 'bid'
			? fetchBidDoneTaskCount(queryInfo)
			: fetchAgentDoneTaskCount(queryInfo)
	}

	fetchTableList({
		queryInfo,
		listType: listType ?? unref(tempListType),
		isReset: false,
		isFirst,
	})
}
const handleUpdateList = () => {
	setTaskLoading(true)
	const typeList = unref(tempQueryInfo)?.[unref(getActiveTab)]?.type_key_list
	console.log(typeList, 'typeList')
	debugger
	fetchTaskCount(unref(getActiveTab))
	debugger
	fetchApplyFilterList().then(() => {
		if (typeList?.length) {
			const typeListArr = typeList.split(',')
			const optionsListRefArr = optionsListRef.value.map(v => v.value)
			const newTypeListArr: any = []
			typeListArr.forEach((item: any) => {
				if (optionsListRefArr.includes(item)) {
					newTypeListArr.push(item)
				}
			})
			checkedListRef.value = newTypeListArr
			if (!unref(checkedListRef).length) {
				handleSearch({ type_key_list: '' })
			} else {
				handleSearch({})
			}
		} else {
			handleSearch({})
		}
	})
	fetchCountAgentTask({})
}
window.updatePortalList = handleUpdateList

const {
	rowKeyRef,
	columnsRef,
	rowSelection,
	// selectedRows,
	hasRowSelection,
	handleEditDraft,
	handleOperateRow,
	handleTableChange,
} = useTable({
	tenantDetail,
	activeTab: getActiveTab,
	onGetList: handleSearch,
	tableElRef,
	toolElRef,
	toolElRef2,
	tempQueryInfo,
})

// watch(
// 	router,
// 	() => {
// 		console.log('router', router)
// 		handleChangeTask(sessionStorage.getItem('processcenter_name') as any)
// 	},
// 	{ deep: true }
// )

// 重置数据k
const handleResetData = () => {
	optionsListRef.value = []
	checkedListRef.value = []
	totalTaskTypeRef.value = {}
	listDataRef.value = []
	tempQueryInfo.value = {}
	tempListType.value = ''

	handleClearSelect()
}

// 强更新页面数据
const updateProcessCenter = () => {
	// 初始化搜索条件
	let queryInfo = unref(tempQueryInfo)?.[unref(getActiveTab)]
	if (taskTypeEnum.Apply === unref(getActiveTab)) {
		queryInfo = {
			...queryInfo,
			status: taskSelect[taskTypeEnum.Apply]?.[1]?.value,
		}
	}
	handleResetData()
	if (unref(getActiveTab) === 'DoneTask') {
		initProcessCenter(unref(getActiveTab), {
			time_sort: 'desc',
			...queryInfo,
			type_key_list: store.state.firterAfterDate[unref(getActiveTab)][
				unref(doneType)
			]
				? store.state.firterAfterDate[unref(getActiveTab)][
						unref(doneType)
				  ].join(',')
				: '',
		})
	} else {
		initProcessCenter(unref(getActiveTab), {
			time_sort: 'desc',
			...queryInfo,
			type_key_list: store.state.firterAfterDate[unref(getActiveTab)]
				? store.state.firterAfterDate[unref(getActiveTab)].join(',')
				: '',
		})
	}
}

// 切换任务类型
const handleChangeTask = debounce((activeKey: string) => {
  if (activeKey === 'TaskNotice') {
    if (!isChangeLayout.value) {
      isChangeLayout.value = !isChangeLayout.value
      isChangeLayout.value
        ? localStorage.setItem('processCenterLayout', 'Top-Bottom')
        : localStorage.setItem('processCenterLayout', 'Left-Right')
    }
  }
  noticeType.value = 'flow'

	const tabDefaultValue = localStorage.getItem('tabDefaultValue') || '{}'
	const pageSize = JSON.parse(tabDefaultValue)[activeKey]?.pageSize || 20
	pageSizeRef.value = pageSize
	setTaskLoading(true)
	setActiveTab('')
	setTimeout(() => {
		localStorage.activeProcessKey = activeKey
		setActiveTab(activeKey)

		updateProcessCenter()
		const tabData = {
			status: 'approve',
			time_sort: 'desc',
			start_time_sort: '',
		}
		if (unref(getActiveTab) === 'Apply') {
			fetchApplyCount(tabData)
		}
		if (unref(getActiveTab) === 'TaskNotice') {
			fetchTaskNoticeCount(tabData)
		}
		if (unref(getActiveTab) === 'DoneTask' && unref(doneType) === 'own') {
			fetchDoneTaskCount(tabData)
		}
	})
})
watch(taskCountRef, value => {
	if (!value.filter(item => item.route_name === getActiveTab.value).length) {
		getActiveTab.value = 'TodoTask'
		handleChangeTask(getActiveTab.value)
	}
})

watch(columnsRef, value => {
	try {
		value.forEach(item => {
					if (item.dataIndex=== 'submit_date'||item.dataIndex=== "start_time") {
						item.sorter = false
						return
					}
				})
	} catch (error) {
	}
	})

const userNotifySizeChange = (current: number, pageSize: number) => {
  userNotifyPageNum.value = current
  userNotifyPageSize.value = pageSize
  fetchUserAllNotify(userNotifyPageNum.value,userNotifyPageSize.value,userInfo.value.id, null)
}

const userNotifyTableChange = () => {
  fetchUserAllNotify(userNotifyPageNum.value,userNotifyPageSize.value,userInfo.value.id, null)
}

//每页条请求
const onShowSizeChange = (current: number, pageSize: number): void => {
	let tabDefaultValue = JSON.parse(
		localStorage.getItem('tabDefaultValue') || '{}'
	)
	tabDefaultValue = Object.assign(tabDefaultValue, {
		[unref(getActiveTab)]: { pageSize: pageSize },
	})
	localStorage.setItem('tabDefaultValue', JSON.stringify(tabDefaultValue))
	pageIndexRef.value = current
	pageSizeRef.value = pageSize
	// 表头左上角checkbox取消选中
	titleCheckAll.value = false
	titleIndeterminate.value = false
	selectedRows.value = []

	fetchTableList({
		isFirst: false,
		queryInfo: unref(tempQueryInfo)?.[unref(getActiveTab)] ?? {
			status: 'approve',
			time_sort: 'desc',
		},
	})
}
const tableChange = (e: number): void => {
	// 表头左上角checkbox取消选中
	titleCheckAll.value = false
	titleIndeterminate.value = false
	selectedRows.value = []
	fetchTableList({
		isFirst: false,
		queryInfo: unref(tempQueryInfo)?.[unref(getActiveTab)] ?? {
			status: 'approve',
			time_sort: 'desc',
		},
	})
}

// 知会批量已读
const handleBatchAllRead = () => {
	batchAllReaded(unref(tempQueryInfo)[unref(getActiveTab)])
	unref(toolElRef).clearParentInput()
	// unref(toolElRef2).clearParentInput()
}

// 批量同意操作
const handleBatchAgree = (resolve: any, reject: any) => {
	batchAgree(unref(selectedRows), unref(getActiveTab), resolve, reject).then(
		data => {
			if (data) {
				const successResult: any = data.filter((item: any) => {
					return item.code === '000000'
				})
				const faildResult: any = data.filter((item: any) => {
					return item.code !== '000000'
				})
				const typeList =
					unref(tempQueryInfo)?.[unref(getActiveTab)]?.type_key_list

				if (!faildResult.length) {
					handleSetSelectState(successResult)
					message.success(
						iTrans(
							'pages.process.successTip',
							`成功处理 ${successResult.length} 条单据`,
							{ count: successResult.length }
						)
					)
					fetchCountAgentTask({})
				} else {
					handleSetSelectState(faildResult)
					message.warning(
						iTrans(
							'pages.process.warnTip',
							`成功处理 ${successResult.length} 条单据，失败 ${faildResult.length} 条单据`,
							{ success: successResult.length, failed: faildResult.length }
						)
					)
					if (unref(getActiveTab) === taskTypeEnum.AgentTodo) {
						fetchCountAgentTask({
							type_key_list: typeList,
						})
					}
				}
				const type = 'batchAgree'
				fetchApplyFilterList(type).then(() => {
					if (typeList?.length) {
						const typeListArr = typeList.split(',')
						const optionsListRefArr = optionsListRef.value.map(v => v.value)
						const newTypeListArr: any = []
						typeListArr.forEach((item: any) => {
							if (optionsListRefArr.includes(item)) {
								newTypeListArr.push(item)
							}
						})
						checkedListRef.value = newTypeListArr
						if (!unref(checkedListRef).length) {
							handleSearch({ type_key_list: '' })
						} else {
							handleSearch({})
						}
					} else if (!faildResult.length) {
						handleSearch({})
					} else {
						handleSearch(
							{
								type_key_list: typeList,
							},
							'',
							false
						)
					}
				})
				fetchTaskCount(unref(getActiveTab))
			}
		}
	)
}
// 草稿箱删除
const handleDeleteDraft = async (
	draftIds: string[],
	resolve?: any,
	reject?: any
) => {
	deleteDraft(draftIds, resolve, reject).then(data => {
		if (data) {
			fetchTaskCount(unref(getActiveTab))
			handleSearch({})
		}
	})
}
const onDelete = (record: any) => {
	record.currentLineHightFlag = true
	Modal.confirm({
		title: iTrans('pages.process.batchDeleteTip', `确认删除已选中的表单？`),
		content: '',
		icon: createVNode(ExclamationCircleOutlined),
		okText: iTrans('common.confirm', '确认'),
		cancelText: iTrans('common.cancel', '取消'),
		onOk() {
			handleDeleteDraft([record?.draft_id])
		},
		onCancel() {
			record.currentLineHightFlag = false
		},
	})
}
const noticeTypeChange = (status: any) => {
  if (status === 'todo') {
    userNotifyPageNum.value = 1
    userNotifyPageSize.value = 10
    fetchUserAllNotify(userNotifyPageNum.value,userNotifyPageSize.value,userInfo.value.id,null)
  } else {

  }
  noticeType.value = status
}

const updateTypeKeyListEvent = () => {
	unref(tempQueryInfo)[unref(getActiveTab)].type_key_list = ''
	handleSearch({})
}
const updateAgentIdEvent = () => {
	unref(tempQueryInfo)[unref(getActiveTab)].agent_id = ''
	handleSearch({})
}

onBeforeUnmount(() => {
	localStorage.removeItem('activeProcessKey')
})
const safariHacks = function () {
	const element: any = document.querySelector('.pok-process-center')
	window.addEventListener('resize', function () {
		element.style.height = 'calc(100% - 24px)'
	})
}
const changeMergeChecked = (status: any) => {
	questChangeMerge(status.target.checked)
	handleUpdateList()
	subjectVisible.value = false
}
// 改变布局
const isChangeLayout = ref(true)
const changeLayout = () => {
	isChangeLayout.value = !isChangeLayout.value
	isChangeLayout.value
		? localStorage.setItem('processCenterLayout', 'Top-Bottom')
		: localStorage.setItem('processCenterLayout', 'Left-Right')
}
onMounted(() => {
  window.addEventListener('storage', e => {
		if (e.key === 'changeActiveProcessKey') {
			localStorage.setItem('activeProcessKey', String(e.newValue))
			handleChangeTask(e.newValue as any)
		}
	})
  fetchUserNotify(1,1,userInfo.value.id, 0)
  fetchUserAllNotify(userNotifyPageNum.value,userNotifyPageSize.value,userInfo.value.id, null)
	safariHacks()
	// }
	//初始化搜索条件
	let queryInfo = unref(tempQueryInfo)?.[unref(getActiveTab)]
	if (taskTypeEnum.Apply === localStorage.activeProcessKey) {
		queryInfo = {
			...queryInfo,
			status: taskSelect[taskTypeEnum.Apply]?.[1]?.value,
		}
	}
	fetchCountAgentTask({})
	initProcessCenter(unref(getActiveTab), {
		...queryInfo,
		status: 'approve',
		time_sort: 'desc',
	})
	let processCenterLayout = localStorage.getItem('processCenterLayout')
	isChangeLayout.value =
		processCenterLayout === null || processCenterLayout === 'Top-Bottom'
			? true
			: false
	//判断是那种头部
	if(store.state.tenant.tenant_auth.app_launcher){
		app_launcher.value=true
	}else{
		app_launcher.value=false
	}
})
</script>
<style lang="less">
.pok-process-table {
	display: flex;
	height: calc(100% - 38px);
}
.subject-title i {
	position: absolute;
	right: 20px;
	top: 10px;
	&:hover,
	&.active {
		color: #4c78fc;
		cursor: pointer;
	}
}
.process-pagination {
	position: absolute;
	width: 100%;
	left: 0;
	bottom: 20px;
	text-align: right;

	.ant-pagination-options-size-changer.ant-select {
		text-align: center;
		margin-right: 24px;
	}
	.ant-pagination-options {
		margin-right: 24px;
	}
}

.title-serial {
	max-height: 22px;
}
.process-center-custom-s {
	.person-info #person-s.primary-text .pok-ellipsis-tooltip {
		max-width: unset;
	}
}
.pok-process-tabs {
	position: relative;
	line-height: 1.2;
}
.changeLayout {
	position: absolute;
	top: 24px;
	right: 24px;
	font-weight: 400;
	font-size: 12px;
	color: #1f2329;
	border: 1px solid #dee0e3;
	border-radius: 4px;
	padding: 0 8px;
	height: 32px;
	line-height: 32px;
	display: flex;
	&:hover {
		cursor: pointer;
	}
	.changeLayout-text {
		display: flex;
		align-items: center;
		.layout-icon {
			width: 16px;
			height: 16px;
			line-height: 19px;
			color: #2b2f36;
			margin-right: 5px;
			font-size: 16px;
		}
	}
}
.ant-tabs-nav .ant-tabs-tab {
	padding-bottom: 16px;
}
.ant-tabs-tab {
	margin: 0 36px 0 0;
}
.pok-process-layout .ant-tabs-bar {
	border-bottom-color: #dee0e3 !important;
	margin: 0;
}
.ant-radio-button-wrapper {
	width: 90px;
	padding: 0 15px;
	text-align: center;
}
.pok-process-table-right {
	overflow: auto;
	.ant-table.ant-table-bordered > .ant-table-container {
		border-left: none;
	}
}
</style>
